<?php

namespace app\api\library;

use think\Exception;
use Tinywan\Jwt\JwtToken;

class UserAuth
{
    private $_user = null;
    private $_user_id = null;

    private function __construct()
    {
        $this->init();
    }

    public static function instance()
    {
        $request = request();
        if (!$request) {
            return new static();
        }
        if (!$request->UserAuth) {
            $request->UserAuth = new static();
        }
        return $request->UserAuth;
    }

    /**
     * @throws Exception
     */
    public function init()
    {
        $user = JwtToken::getUser();
        if($user['status'] == 0){
            JwtToken::clear();
            JwtToken::clear(JwtToken::TOKEN_CLIENT_MOBILE);
            throw new Exception("该账号已在其他设备登录，强制下线！");
        }
        $this->_user = $user;
        $this->_user_id = $user['id'];
    }

    public function getUser()
    {
        return $this->_user;
    }

    public function getUserId()
    {
        return $this->_user_id;
    }
}